package com.yixuan.mt.common.local.objects;

import com.yixuan.mt.common.constant.ObjectsConstant;
import com.yixuan.mt.common.entity.Objects;

import java.io.*;

public class ObjectsMeta {

    public static void createObjectsMeta(String objectPath, File ObjectFile) throws IOException {
        File objectMetaFile = new File(ObjectsConstant.OBJECTS_META_FILE_SUFFIX_PATH + objectPath + ObjectsConstant.OBJECTS_META_FILE_SUFFIX);
        if (!objectMetaFile.exists()) {
            objectMetaFile.getParentFile().mkdirs();
            objectMetaFile.createNewFile();
        }
        // 初始化对象元数据
        addBasicInfoToObjectsMeta(objectMetaFile, ObjectFile);
    }

    public static void addBasicInfoToObjectsMeta(File ObjectMetaFile, File objectFile) throws IOException {
        FileOutputStream fos = new FileOutputStream(ObjectMetaFile);
        DataOutputStream dos = new DataOutputStream(fos);
        try (fos; dos) {
            // 写入上次修改时间
            dos.writeLong(objectFile.lastModified());
            // 写入文件大小
            dos.writeLong(objectFile.length());
        }
    }

    public static Objects getBasicInfoFromObjectsMeta(String objectPath) throws IOException {
        File file = new File(ObjectsConstant.OBJECTS_META_FILE_SUFFIX_PATH + objectPath + ObjectsConstant.OBJECTS_META_FILE_SUFFIX);
        FileInputStream fis = new FileInputStream(file);
        DataInputStream dis = new DataInputStream(fis);
        try (fis; dis) {
            Objects objectBasicInfo = new Objects();
            // 对象名
            objectBasicInfo.setName(objectPath.substring(objectPath.lastIndexOf("/") + 1));
            // 读取上次修改时间
            objectBasicInfo.setLastModifiedTime(dis.readLong());
            // 读取文件大小
            objectBasicInfo.setSize(dis.readLong());
            return objectBasicInfo;
        }
    }
}
